package cn.daomeng.firebird.core.utils;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * AES工具类
 * @author fan.yang
 * @since 2013/11/19
 */
public class AesUtil {

    private static final Logger logger = LoggerFactory.getLogger(AesUtil.class);

    private static final String SKEY = "CD7F7D09DF75502B";

    private static final int LENGTH_16 = 16;

    /**
     * 加密
     * @author Qin.Siliang
     * @since 14:50 2018/11/19
     * @Param [sSrc]
     * @return java.lang.String
     **/
    public static String encrypt(String sSrc) throws Exception {
        if (SKEY == null) {
            logger.info("Key为空null");
            return null;
        }
        // 判断Key是否为16位
        if (SKEY.length() != LENGTH_16) {
            logger.info("Key长度不是16位");
            return null;
        }
        byte[] raw = SKEY.getBytes(Constants.ENCODING_UTF_8);
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        //"算法/模式/补码方式"
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        //使用CBC模式，需要一个向量iv，可增加加密算法的强度
        IvParameterSpec iv = new IvParameterSpec("0102030405060708".getBytes(Constants.ENCODING_UTF_8));
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
        byte[] encrypted = cipher.doFinal(sSrc.getBytes(Constants.ENCODING_UTF_8));
        //此处使用BAES64做转码功能，同时能起到2次加密的作用。
        return Base64.encodeBase64String(encrypted);
    }

    /**
     * 解密
     * @author Qin.Siliang
     * @since 14:51 2018/11/19
     * @Param [sSrc]
     * @return java.lang.String
     **/
    public static String decrypt(String sSrc) throws Exception {
        try {
            // 判断Key是否正确    
            if (SKEY == null) {
                logger.info("Key为空null");
                return null;
            }
            // 判断Key是否为16位
            if (SKEY.length() != LENGTH_16) {
                logger.info("Key长度不是16位");
                return null;
            }
            byte[] raw = SKEY.getBytes("ASCII");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            IvParameterSpec iv = new IvParameterSpec("0102030405060708".getBytes(Constants.ENCODING_UTF_8));
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            //先用bAES64解密
            byte[] encrypted1 = Base64.decodeBase64(sSrc);
            try {
                byte[] original = cipher.doFinal(encrypted1);
                String originalString = new String(original,Constants.ENCODING_UTF_8);
                return originalString;
            } catch (Exception e) {
                logger.info(e.toString());
                return null;
            }
        } catch (Exception e) {
            logger.error(e.toString(), e);
            return null;
        }
    }
}
